/*
 * Copyright (C) 2012 Компания ВИТ. web: http://diasled.ru Е-mail:  vit@diasled.ru
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * FOutlineZone.java
 *
 * Created on Mar 13, 2012, 6:38:24 PM
 */
package ru.apertum.diasled.forms;

import com.jogamp.newt.event.KeyEvent;
import java.awt.Canvas;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;
import ru.apertum.diasled.cfg.MyPoint;
import ru.apertum.diasled.cfg.Outline;
import ru.apertum.diasled.cfg.Zone;
import ru.apertum.diasled.redactor.RouteZoneTableModel;

/**
 *
 * @author Evgeniy Egorov
 */
public class FOutlineZone extends javax.swing.JDialog {

    public static FOutlineZone getInstance() {
        return FOutlineZoneHolder.INSTANCE;
    }

    private static class FOutlineZoneHolder {

        private static final FOutlineZone INSTANCE = new FOutlineZone(null, false);
    }

    /** Creates new form FOutlineZone */
    private FOutlineZone(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        try {
            setIconImage(ImageIO.read(DiasledView.class.getResource("/ru/apertum/diasled/forms/resources/redactor.png")));
        } catch (IOException ex) {
            System.err.println(ex);
        }

        // свернем по esc
        getRootPane().registerKeyboardAction(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        },
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_IN_FOCUSED_WINDOW);

        listZone.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (outline != null) {
                    for (Zone zone : outline.getZone()) {
                        if (zone.getNum() == listZone.getSelectedIndex()) {
                            tableRoute.setModel(new RouteZoneTableModel(zone));
                            if (canvas != null) {
                                java.awt.EventQueue.invokeLater(new Runnable() {

                                    public void run() {
                                        canvas.repaint();
                                    }
                                });
                            }
                            break;
                        }
                    }
                }
            }
        });

    }
    private Outline outline = null;
    private Canvas canvas = null;
    
    public JList<Zone> getListZone(){
        return listZone;
    }

    public void loadConfig(final Outline outline, Canvas canvas) {
        setTitle("Зоны контура");
        this.outline = outline;
        this.canvas = canvas;
        listZone.setModel(new DefaultComboBoxModel(outline.getZone().toArray(new Zone[0])));
        if (listZone.getModel().getSize() != 0) {
            listZone.setSelectedIndex(0);
        } else {
            tableRoute.setModel(new DefaultTableModel());
        }
    }

    public void saveConfig(Outline outline) {
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jPopupMenu2 = new javax.swing.JPopupMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jPanel1 = new javax.swing.JPanel();
        buttonCancel = new javax.swing.JButton();
        buttonRefresh = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        listZone = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableRoute = new javax.swing.JTable();

        jPopupMenu1.setName("jPopupMenu1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(ru.apertum.diasled.Diasled.class).getContext().getActionMap(FOutlineZone.class, this);
        jMenuItem1.setAction(actionMap.get("setZoneCount")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        jPopupMenu1.add(jMenuItem1);

        jPopupMenu2.setName("jPopupMenu2"); // NOI18N

        jMenuItem2.setAction(actionMap.get("insertPoint")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jPopupMenu2.add(jMenuItem2);

        jMenuItem3.setAction(actionMap.get("removePoint")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        jPopupMenu2.add(jMenuItem3);

        setAlwaysOnTop(true);
        setName("Form"); // NOI18N

        jPanel1.setBorder(new javax.swing.border.MatteBorder(null));
        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ru.apertum.diasled.Diasled.class).getContext().getResourceMap(FOutlineZone.class);
        buttonCancel.setText(resourceMap.getString("buttonCancel.text")); // NOI18N
        buttonCancel.setName("buttonCancel"); // NOI18N
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        buttonRefresh.setText(resourceMap.getString("buttonRefresh.text")); // NOI18N
        buttonRefresh.setName("buttonRefresh"); // NOI18N
        buttonRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRefreshActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(buttonRefresh)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addComponent(buttonCancel)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonCancel)
                    .addComponent(buttonRefresh))
                .addContainerGap())
        );

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPane1.border.title"))); // NOI18N
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        listZone.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listZone.setComponentPopupMenu(jPopupMenu1);
        listZone.setName("listZone"); // NOI18N
        jScrollPane1.setViewportView(listZone);

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jScrollPane2.border.title"))); // NOI18N
        jScrollPane2.setName("jScrollPane2"); // NOI18N

        tableRoute.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "X", "Y"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tableRoute.setComponentPopupMenu(jPopupMenu2);
        tableRoute.setName("tableRoute"); // NOI18N
        jScrollPane2.setViewportView(tableRoute);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        setVisible(false);
    }//GEN-LAST:event_buttonCancelActionPerformed

    private void buttonRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRefreshActionPerformed
        if (canvas != null) {
                java.awt.EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        canvas.repaint();
                    }
                });
            }
    }//GEN-LAST:event_buttonRefreshActionPerformed

    @Action
    public void setZoneCount() {
        setAlwaysOnTop(false);
        Integer cnt = (Integer) JOptionPane.showInputDialog(this, "Количество зон:", "Выбери цифру", JOptionPane.QUESTION_MESSAGE, null, new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}, 0);
        if (cnt != null) {
            int d = outline.getZone().size() - cnt;
            if (d > 0) {
                for (int i = 0; i < d; i++) {
                    outline.getZone().removeLast();
                }
            } else {
                for (int i = 0; i > d; i--) {
                    outline.getZone().addLast(new Zone(outline.getZone().size()));
                }
            }
        }
        listZone.setModel(new DefaultComboBoxModel(outline.getZone().toArray(new Zone[0])));
        setAlwaysOnTop(true);
        if (listZone.getModel().getSize() != 0) {
            listZone.setSelectedIndex(0);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonRefresh;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JPopupMenu jPopupMenu2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList listZone;
    private javax.swing.JTable tableRoute;
    // End of variables declaration//GEN-END:variables

    void addFirstPOint(MyPoint myPoint) {
        ((RouteZoneTableModel) (tableRoute.getModel())).addFirst(myPoint);
    }

    void addLastPOint(MyPoint myPoint) {
        ((RouteZoneTableModel) (tableRoute.getModel())).addLast(myPoint);
    }

    @Action
    public void removePoint() {
        if (tableRoute.getSelectionModel().getLeadSelectionIndex() != -1 && tableRoute.getModel() instanceof RouteZoneTableModel) {
            final ArrayList<MyPoint> ap = new ArrayList<>();
            for (int i : tableRoute.getSelectedRows()) {
                ap.add(new MyPoint((int) tableRoute.getModel().getValueAt(i, 0), (int) tableRoute.getModel().getValueAt(i, 1)));
            }
            for (MyPoint point : ap) {
                ((RouteZoneTableModel) (tableRoute.getModel())).remove(point);
            }
            ((RouteZoneTableModel) (tableRoute.getModel())).fireTableDataChanged();
            if (canvas != null) {
                java.awt.EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        canvas.repaint();
                    }
                });
            }
        }
    }

    @Action
    public void insertPoint() {
        if (tableRoute.getSelectionModel().getLeadSelectionIndex() != -1 && tableRoute.getModel() instanceof RouteZoneTableModel) {

            int x = (int) tableRoute.getModel().getValueAt(tableRoute.getSelectionModel().getLeadSelectionIndex(), 0);
            int y = (int) tableRoute.getModel().getValueAt(tableRoute.getSelectionModel().getLeadSelectionIndex(), 1);

            int s = tableRoute.getSelectionModel().getLeadSelectionIndex() + 1;
            ((RouteZoneTableModel) (tableRoute.getModel())).add(s, new MyPoint(x + 10, y + 10));
            ((RouteZoneTableModel) (tableRoute.getModel())).fireTableDataChanged();
            tableRoute.getSelectionModel().setSelectionInterval(s, s);
            if (canvas != null) {
                java.awt.EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        canvas.repaint();
                    }
                });
            }
        }
    }
}
